<template>
  <div class="flex h-full flex-1 gap-3">
    <!-- 左侧来电信息和通话控制 -->
    <div class="w-1/4 rounded-lg">
      <!-- 来电信息头部 -->
      <div class="bg-white rounded-lg p-3 mb-3">
        <div class="flex items-center justify-between mb-4">
            <div class="text-lg">来电信息</div>
            <div class="flex items-center gap-2">
              <el-tag :type="callStatus.type">{{ callStatus.text }}</el-tag>
              <el-switch v-model="isConnected" active-text="打开" inactive-text="关闭" />
            </div>
        </div>
        <!-- 来电号码信息 -->
        <div class="mb-4">
          <div class="text-2xl font-bold text-blue-500 text-center">{{ currentCall.phone }}</div>
          <div class="text-gray-500 text-center">{{ currentCall.type }}</div>
          <div class="mt-2 text-sm">
              <div class="flex justify-between mb-1">
              <span>通话时长：</span>
              <span class="text-blue-500">{{ callDuration }}</span>
              </div>
              <div class="flex justify-between mb-1">
              <span>等待时长：</span>
              <span class="text-orange-500">{{ waitDuration }}</span>
              </div>
          </div>
        </div>
        <!-- 通话控制按钮 -->
        <div class="flex gap-2 mb-4 justify-center">
          <el-button 
              size="small"
              type="success" 
              :icon="Phone"
              :disabled="!canAnswer"
              @click="handleAnswer">
              接听
          </el-button>
          <el-button 
              size="small"
              type="danger" 
              :icon="PhoneFilled"
              :disabled="!canHangup"
              @click="handleHangup">
              挂断
          </el-button>
          <el-button 
              size="small"
              type="warning" 
              :icon="Switch"
              :disabled="!canTransfer"
              @click="handleTransfer">
              转接
          </el-button>
        </div>
      </div>
      <!-- 新建跟进记录 -->
      <div class="mb-3 bg-white rounded-lg p-3">
        <div class="text-base mb-2">新建跟进记录</div>
        <el-input
          type="textarea"
          v-model="followUpContent"
          :rows="4"
          placeholder="请输入与该客户的沟通跟进内容"
        />
        <div class="flex justify-center mt-2">
          <el-button type="primary" size="small" @click="submitFollowUp">提交</el-button>
        </div>
      </div>

      <!-- 跟进记录列表 -->
      <div class="h-78 bg-white rounded-lg p-3 overflow-y-auto">
        <div class="text-base mb-2">跟进记录</div>
        <div class="records-scroll-container">
          <el-timeline>
            <el-timeline-item
              v-for="record in followUpRecords"
              :key="record.time"
              :timestamp="record.time"
              :type="getTimelineItemType(record)"
            >
              <div class="timeline-content p-2">
                <div class="flex items-center justify-between mb-2">
                  <span class="font-medium text-gray-700">{{ record.name }}</span>
                  <el-tag size="small" :type="getStatusType(record)">
                    {{ record.status || '已完成' }}
                  </el-tag>
                </div>
                <div class="text-gray-600 text-sm whitespace-pre-wrap">{{ record.content }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>

    <!-- 右侧客户信息和通话记录 -->
    <div class="flex-1 bg-white rounded-lg p-3">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="客户基本信息" name="basic">
          <el-form :model="customerInfo" label-width="100px">
            <div class="grid grid-cols-3 gap-4">
              <el-form-item label="客户编号">
                <el-input v-model="customerInfo.number" placeholder="52" disabled/>
              </el-form-item>
              <el-form-item label="客户姓名">
                <el-input v-model="customerInfo.name" placeholder="9002" />
              </el-form-item>
              <el-form-item label="客户电话">
                  <el-input v-model="customerInfo.phone" placeholder="9002" />
              </el-form-item>
              <el-form-item label="客户标签">
                <el-select v-model="customerInfo.tags" placeholder="请选择" clearable>
                  <el-option label="VIP客户" value="vip" />
                  <el-option label="超级VIP客户" value="supervip" />
                </el-select>
              </el-form-item>
              <el-form-item label="客户电话2">
                <el-input v-model="customerInfo.phone2" placeholder="1级" />
              </el-form-item>
              <el-form-item label="客户类别">
                <el-input v-model="customerInfo.category" placeholder="9002" />
              </el-form-item>
              <el-form-item label="客户性别">
                <el-select v-model="customerInfo.gender" placeholder="测试数据111">
                  <el-option label="男" value="male" />
                  <el-option label="女" value="female" />
                </el-select>
              </el-form-item>
              <el-form-item label="客户信息">
                <el-input v-model="customerInfo.info" placeholder="测试数据111" />
              </el-form-item>
              <el-form-item label="客户年龄">
                <el-input v-model="customerInfo.age" placeholder="青年" />
              </el-form-item>
              <el-form-item label="客户区域" required>
                <el-input v-model="customerInfo.region" placeholder="9002" />
              </el-form-item>
              <el-form-item label="客户地址">
                <el-input v-model="customerInfo.address" placeholder="9002" />
              </el-form-item>
            </div>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="customerInfo.remarks" :rows="4" placeholder="9002" />
            </el-form-item>

            <!-- 标签展示区域 -->
            <div class="mt-3 flex items-center">
              <el-tag
                v-for="(tag, index) in selectedTags"
                :key="tag"
                class="mr-2"
                :type="getTagType(index)"
                closable
                @close="removeTag(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-button type="info" plain size="small" @click="tagDialogVisible = true">
                添加标签
              </el-button>
            </div>

            <!-- 底部按钮 -->
            <div class="flex justify-center gap-4 mt-6">
              <el-button type="primary" @click="saveCustomerInfo">保存信息</el-button>
              <el-button type="primary" @click="sendMessage">发送短信</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 转接弹窗 -->
    <Drawer 
      v-model="transferDialogVisible"
      title="转接通话"
      width="300px"
      :confirmText="'确认转接'"
      :cancelText="'取消'"
      @confirm="confirmTransfer"
      @cancel="transferDialogVisible = false">
      <el-form :model="transferForm" label-width="100px">
        <el-form-item label="转接类型">
          <el-radio-group v-model="transferForm.type">
            <el-radio label="doctor">医生</el-radio>
            <el-radio label="department">科室</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="转接对象">
          <el-select v-model="transferForm.target" filterable placeholder="请选择">
            <el-option
              v-for="item in transferTargets"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转接原因">
          <el-input type="textarea" v-model="transferForm.reason" :rows="3" />
        </el-form-item>
      </el-form>
    </Drawer>
    <!-- 添加标签 -->
    <Drawer 
      v-model="tagDialogVisible"
      title="添加标签"
      width="300px"
      :confirmText="'确认'"
      :cancelText="'取消'"
      @confirm="confirmTag"
      @cancel="tagDialogVisible = false">
      <el-input v-model="tagInput" placeholder="请输入标签" />
    </Drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated } from 'vue'
import { useTabStore } from '../../stores/tabStore'
import { Phone, PhoneFilled, Switch, VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Drawer from '@/components/common/Drawer.vue'

// 定义组件名称
defineOptions({
  name: 'TelephoneConsultation'
});

const tabStore = useTabStore()
const isConnected = ref(false)
const activeTab = ref('basic')
const followUpContent = ref('')

// 跟进记录数据
const followUpRecords = ref([
  {
    name: '客服(1001)',
    time: '2024-07-22 09:25:55',
    content: '9002'
  },
  {
    name: '客服(1001)',
    time: '2024-07-22 09:25:53',
    content: '900'
  }
])

// 客户信息表单数据
const customerInfo = reactive({
  number: '52',
  name: '9002',
  phone: '9002',
  tags: '',
  phone2: '1级',
  category: '9002',
  gender: '测试数据111',
  info: '测试数据111',
  age: '青年',
  region: '9002',
  address: '9002',
  remarks: '9002'
})

// 已选标签
const selectedTags = ref(['VIP客户', '超级VIP客户', 'what can i say', '要回客户'])

// 通话状态
const currentCall = reactive({
  phone: '9002',
  type: '内部分机',
  startTime: null as Date | null,
  status: 'waiting' // waiting, connected, ended
})

const callStatus = computed(() => {
  switch (currentCall.status) {
    case 'waiting':
      return { text: '等待接听', type: 'warning' }
    case 'connected':
      return { text: '通话中', type: 'success' }
    case 'ended':
      return { text: '通话结束', type: 'info' }
    default:
      return { text: '未知状态', type: 'info' }
  }
})

// 按钮状态控制
const canAnswer = computed(() => currentCall.status === 'waiting')
const canHangup = computed(() => currentCall.status === 'connected')
const canTransfer = computed(() => currentCall.status === 'connected')

// 通话时长计时
const callDuration = ref('00:00:00')
const waitDuration = ref('00:00:00')
let durationTimer: number | null = null

// 转接相关
const transferDialogVisible = ref(false)
const transferForm = reactive({
  type: 'doctor',
  target: '',
  reason: ''
})
const transferTargets = ref([
  { id: 1, name: '张医生 - 内科' },
  { id: 2, name: '李医生 - 外科' },
  { id: 3, name: '内科门诊' },
  { id: 4, name: '外科门诊' }
])

// 通话记录查询
const searchForm = reactive({
  dateRange: [],
  callType: ''
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const callRecords = ref([
  {
    date: '2024-01-20 14:23:15',
    duration: '00:05:23',
    type: '咨询',
    agent: '客服(1001)',
    status: '已完成',
    content: '患者咨询就医流程，已详细说明预约挂号方式。',
    result: '已解决',
    recordingUrl: 'path/to/recording.mp3'
  }
])

// 接听
const handleAnswer = () => {
  currentCall.status = 'connected'
  currentCall.startTime = new Date()
  startTimer()
  ElMessage.success('已接听来电')
}
// 挂断
const handleHangup = () => {
  currentCall.status = 'ended'
  stopTimer()
  if (isRecording.value) {
    toggleRecording()
  }
  ElMessage.success('通话已结束')
}
// 转接
const handleTransfer = () => {
  transferDialogVisible.value = true
}
// 转接确认
const confirmTransfer = () => {
  ElMessage.success(`正在转接至${transferForm.type === 'doctor' ? '医生' : '科室'}`)
  transferDialogVisible.value = false
}
// 通话时长计时
const startTimer = () => {
  if (durationTimer) return
  const startTime = new Date()
  durationTimer = window.setInterval(() => {
    const diff = new Date().getTime() - startTime.getTime()
    const hours = Math.floor(diff / 3600000)
    const minutes = Math.floor((diff % 3600000) / 60000)
    const seconds = Math.floor((diff % 60000) / 1000)
    callDuration.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }, 1000)
}
// 通话时长计时停止
const stopTimer = () => {
  if (durationTimer) {
    clearInterval(durationTimer)
    durationTimer = null
  }
}

// 生命周期
onMounted(() => {
  // 可以在这里初始化WebSocket连接等
//   window.WebSocket = require('ws')
    console.log('页面加载')
})

onUnmounted(() => {
})

// 提交跟进记录
const submitFollowUp = () => {
  if (!followUpContent.value) return
  followUpRecords.value.unshift({
    name: '客服(1001)',
    time: new Date().toLocaleString(),
    content: followUpContent.value
  })
  followUpContent.value = ''
}
const tagDialogVisible = ref(false)
const tagInput = ref('')
// 移除标签
const removeTag = (tag) => {
  selectedTags.value = selectedTags.value.filter(t => t !== tag)
}
// 确认标签
const confirmTag = () => {
  if (tagInput.value) {
    selectedTags.value.push(tagInput.value)
    tagInput.value = ''
  }
  tagDialogVisible.value = false
}

// 保存客户信息
const saveCustomerInfo = () => {
  // 实现保存信息的逻辑
}

// 发送短信
const sendMessage = () => {
  // 实现发送短信的逻辑
}

// 获取时间线项的类型
const getTimelineItemType = (record) => {
  // 根据记录状态返回不同的类型
  switch(record.status?.toLowerCase()) {
    case 'pending':
    case '待处理':
      return 'warning';
    case 'processing':
    case '处理中':
      return 'primary';
    case 'completed':
    case '已完成':
      return 'success';
    default:
      return '';
  }
};

// 获取状态标签的类型
const getStatusType = (record) => {
  switch(record.status?.toLowerCase()) {
    case 'pending':
    case '待处理':
      return 'warning';
    case 'processing':
    case '处理中':
      return '';
    case 'completed':
    case '已完成':
      return 'success';
    default:
      return 'info';
  }
};
// 获取标签的类型
const getTagType = (index) => {
  switch(index) {
    case 0:
      return 'success';
    case 1:
      return 'warning';
    case 2:
      return 'primary';
    case 3:
      return 'danger';
    default:
      return 'info';
  }
}

// 生命周期钩子
onActivated(() => {
  console.log('TelephoneConsultation activated');
  // 组件被激活时的处理逻辑
});

onDeactivated(() => {
  console.log('TelephoneConsultation deactivated');
  // 组件被停用时的处理逻辑
});
</script>

<style lang="scss" scoped>
.timeline-content {
  @apply bg-white rounded-lg shadow-sm border border-gray-100;
  
  &:hover {
    @apply shadow-md transition-shadow duration-300;
  }
}

:deep(.el-timeline-item__node) {
  @apply border-4;
}

:deep(.el-timeline-item__timestamp) {
  @apply text-gray-500 text-sm;
  
  &.is-top {
    @apply mb-2;
  }
}

:deep(.el-timeline-item__wrapper) {
  @apply pb-6;
}
</style>

